package com.realbrand.net.realbrandpay.ui.activity.wallet.set;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IChangePhone;
import com.realbrand.net.realbrandpay.inter.IGetCode;
import com.realbrand.net.realbrandpay.ui.activity.wallet.personer.AccountActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/6/20.
 */

public class VerifyNewPhoneActivity extends BaseActivity {

    @BindView(R.id.verifyNewPhone_toolbar)
    Toolbar verifyNewPhoneToolbar;
    @BindView(R.id.verifyNewPhone_et_userPhone)
    EditText verifyNewPhoneEtUserPhone;
    @BindView(R.id.verifyNewPhone_et_verifyCode)
    EditText verifyNewPhoneEtVerifyCode;
    @BindView(R.id.verifyNewPhone_bt_sure)
    Button verifyNewPhoneBtSure;
    @BindView(R.id.verifyNewPhone_bt_sendVerifyCode)
    Button verifyNewPhoneBtSendVerifyCode;

    //用户输入的手机号码
    private String UserMobile;
    //请求返回的验证码
    private String verifyCode;
    //用户输入的验证码
    private String verifyCodeByUser;
    //就手机号码
    private String oldMobile;

    private String encode;

    //定时器
    private TimeCount time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        verifyNewPhoneToolbar.setTitle("");
        verifyNewPhoneToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(verifyNewPhoneToolbar);
        verifyNewPhoneToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //获取旧手机号码
        oldMobile = getIntent().getStringExtra("userMobile");
       if (! verifyNewPhoneBtSendVerifyCode.isClickable()){
            verifyNewPhoneBtSendVerifyCode.setClickable(true);
        }
        time = new TimeCount(120000, 1000);
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.verifyphonecode_b_activity;
    }

    @Override
    protected void setOnClick() {
        verifyNewPhoneBtSendVerifyCode.setOnClickListener(this);
        verifyNewPhoneBtSure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //发送验证码
            case R.id.verifyNewPhone_bt_sendVerifyCode:
                //先获取用户输入的手机号码，判断手机号码的格式是否正确，然后再发送验证码
                UserMobile = verifyNewPhoneEtUserPhone.getText().toString();
                verifyNewPhoneBtSendVerifyCode.setClickable(false);
                if (TextUtils.isEmpty(UserMobile)) {
                    Static.toast(VerifyNewPhoneActivity.this, "请输入手机号码");
                } else {
                    if (Static.isMobileNO(UserMobile)) {
                        sendVerifyCode(UserMobile);

                    } else {
                        Static.toast(VerifyNewPhoneActivity.this, "请输入正确的手机号码");
                    }
                }
                break;
            //确定
            case R.id.verifyNewPhone_bt_sure:
                verifyCodeByUser = verifyNewPhoneEtVerifyCode.getText().toString();
                if (TextUtils.isEmpty(verifyCodeByUser)) {
                    Static.toast(VerifyNewPhoneActivity.this, "请输入收到的验证码");
                } else {
                    changePhone(UserMobile);
                }
                break;
        }
    }

    private void changePhone(final String userMobile) {
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add("NewPhoneNumber");
        keyList.add("OldPhoneNumber");
        keyList.add("Verification");
        ArrayList<String> valueList = new ArrayList<>();
        valueList.add(userMobile);
        valueList.add(oldMobile);
        valueList.add(verifyCodeByUser);
        String string = Static.getString(keyList, valueList);
        try {
            encode = URLEncoder.encode(string, "utf-8");
            JSONObject object = new JSONObject();
            try {
                object.put("SOURCE", "VerifyNewPhoneActivity");
                object.put("CREDENTIALS", "0");
                object.put("TERMINAL", "1");
                object.put("INDEX", Static.getDay());
                object.put("METHOD", "ChangePhoneNumber");
                object.put("DATA", encode);
                RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
                Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
                IChangePhone iChangePhone = retrofit.create(IChangePhone.class);
                Call<ResponseBody> call = iChangePhone.changePhone(body);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response == null) {
                            Static.toast(VerifyNewPhoneActivity.this, "网络繁忙");
                        } else {
                            try {
                                String result = response.body().string();
                                L.d(L.TAG, "更改手机号码返回的结果" + result);
                                try {
                                    JSONObject js = new JSONObject(result);
                                    String dataString = js.getString("result");
                                    if ("1".equals(dataString)) {
                                        //表示更改成功
                                        SharedPreferences sharedPreferences = getSharedPreferences("userMassage", MODE_PRIVATE);
                                        SharedPreferences.Editor editor = sharedPreferences.edit();
                                        editor.putString("mobile", userMobile);
                                        editor.commit();
                                        startActivity(new Intent(VerifyNewPhoneActivity.this, AccountActivity.class));
                                        finish();
                                    } else if ("3".equals(dataString)){
                                        Static.toast(VerifyNewPhoneActivity.this,"验证码错误");
                                    }else if ("2".equals(dataString)){
                                        Static.toast(VerifyNewPhoneActivity.this,"验证码已超时");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    //发送验证码
    private void sendVerifyCode(String userMobile) {
        JSONObject object = new JSONObject();
        try {
            object.put("METHOD", "AccountProving");
            object.put("SOURCE", "VerifyNewPhoneActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("UserMobile", userMobile);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(HTTPAPI.BASE_URL)
                    .build();
            IGetCode getCode = retrofit.create(IGetCode.class);
            Call<ResponseBody> call = getCode.getCode(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(VerifyNewPhoneActivity.this, "网络繁忙");
                    } else {
                        try {
                            String result = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                JSONArray data = jsonObject.getJSONArray("DATA");
                                JSONObject json = data.getJSONObject(0);
                                String string = json.getString("result");
                                if ("false".equals(string)) {
                                    //表示该手机号没被注册
                                    time.start();
                                } else if ("true".equals(string)) {
                                    Static.toast(VerifyNewPhoneActivity.this, "该手机号码已被绑定，请重新输入手机号码");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();

                            }
                        } catch (IOException e) {
                            e.printStackTrace();

                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    verifyNewPhoneBtSendVerifyCode.setClickable(true);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            verifyNewPhoneBtSendVerifyCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            verifyNewPhoneBtSendVerifyCode.setClickable(false);
            verifyNewPhoneBtSendVerifyCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }

        @Override
        public void onFinish() {
            verifyNewPhoneBtSendVerifyCode.setText("重新获取验证码");
            verifyNewPhoneBtSendVerifyCode.setClickable(true);
            verifyNewPhoneBtSendVerifyCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
        }
    }
}
